package com.kstech.mp3604.fragments

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.kstech.mp3604.adapter.ErrorInfoAdapter
import com.kstech.mp3604.adapter.GridSpaceItemDecoration
import com.kstech.mp3604.base.BaseDialogFragment
import com.kstech.mp3604.bean.ErrorInfo
import com.kstech.mp3604.data.DbManager
import com.kstech.mp3604.databinding.DialogErrorFragmentBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 故障按钮
 */
class DialogErrorFragment :
    BaseDialogFragment<DialogErrorFragmentBinding>(DialogErrorFragmentBinding::inflate) {
    override fun onInitView() {

        lifecycleScope.launch(Dispatchers.IO) {
            val dataList = DbManager.db.errorInfoDao().queryAllErrorInfo()
            withContext(Dispatchers.Main) {
                if (dataList.size > 0) {
                    binding.emptyDataMsg.visibility = View.GONE
                    updateView(dataList)
                } else {
                    binding.emptyDataMsg.visibility = View.VISIBLE
                    binding.emptyDataMsg.text = "暂无数据"
                }
            }
        }
        binding.apply {
            closeDialog.setOnClickListener {
                dialog!!.cancel()
            }
        }
    }

    private fun updateView(dataList: List<ErrorInfo>) {
        val errorAdapter = ErrorInfoAdapter()
        binding.apply {
            historyRecyclerView.layoutManager = LinearLayoutManager(requireActivity())
            historyRecyclerView.addItemDecoration(GridSpaceItemDecoration(10, 10))
            historyRecyclerView.adapter = errorAdapter
            errorAdapter.submitList(dataList)
        }
    }
}